package main

import (
	"bytes"
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"os"
	"os/exec"
	"time"
)

func main() {
	router := gin.Default()

	router.GET("/deleteqrcode/:num", func(c *gin.Context) {
		number := c.Param("num")
		imgPath := "/Users/kidswant/Desktop/wechat_write_path/" + number + ".jpeg"
		openCmd := "rm"
		cmd := exec.Command(openCmd, imgPath)
		var out bytes.Buffer
		var stderr bytes.Buffer
		cmd.Stdout = &out
		cmd.Stderr = &stderr
		err := cmd.Run()
		if err != nil {
			c.JSON(200, gin.H{
				"message": fmt.Sprint(err) + ": " + stderr.String(),
			})
			return
		}
		c.JSON(200, gin.H{
			"message": "Delete the qrcode success",
		})
	})

	router.GET("/qrcode/:num", func(c *gin.Context) {
		number := c.Param("num")

		if len(number) <= 0 {
			c.JSON(200, gin.H{
				"code": "2001",
				"msg":  "工号不能为空",
			})
			return
		}
		c.Writer.Header().Set("Content-Type", "image/jpeg")
		imgPath := "/Users/kidswant/Desktop/wechat_write_path/" + number + ".jpeg"

		if _, err := os.Stat(imgPath); err == nil {
			// QRCode image exists
			QRCodeImgFile, _ := os.Open(imgPath)
			defer QRCodeImgFile.Close()
			io.Copy(c.Writer, QRCodeImgFile)
			return
		}
		openCmd := "open"
		cmd := exec.Command(openCmd, "-n", "/Applications/WeChat.app", "--args", "processNum"+number)
		var out bytes.Buffer
		var stderr bytes.Buffer
		cmd.Stdout = &out
		cmd.Stderr = &stderr
		err := cmd.Run()
		if err != nil {
			fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
			return
		}
		var timeC int
		for {
			timeC++
			time.Sleep(1 * time.Second)
			if _, err := os.Stat(imgPath); err == nil {
				QRCodeImgFile, err := os.Open(imgPath)
				if err != nil {
					fmt.Println("load image error", err)
				}
				defer QRCodeImgFile.Close()
				io.Copy(c.Writer, QRCodeImgFile)
				break
			}
			if timeC >= 60 {
				break
				fmt.Println("加载二维码失败")
				return
			}
		}
	})

	router.GET("/autoauth", func(c *gin.Context) {

		number := c.Query("workid")
		wxid := c.Query("wxid")

		openCmd := "open"
		cmd := exec.Command(openCmd, "-n", "/Applications/WeChat.app", "--args", "processNum"+number, "usrName"+wxid)
		var out bytes.Buffer
		var stderr bytes.Buffer
		cmd.Stdout = &out
		cmd.Stderr = &stderr
		err := cmd.Run()
		if err != nil {
			fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
			c.JSON(500, gin.H{
				"status": "error auto auth",
				"error":  (fmt.Sprint(err) + ": " + stderr.String()),
			})
			return
		}
		c.JSON(200, gin.H{
			"status": "auto auth",
			"workid": number,
			"wxid":   wxid,
		})
	})

	router.GET("/deleteQRCode", func(c *gin.Context) {

		rmCmd := "rm"
		cmd := exec.Command(rmCmd, "-rf", "/Users/kidswant/Desktop/wechat_write_path")
		var out bytes.Buffer
		var stderr bytes.Buffer
		cmd.Stdout = &out
		cmd.Stderr = &stderr
		err := cmd.Run()
		if err != nil {
			fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
			c.JSON(500, gin.H{
				"status": "Delete all qrcode file error",
				"error":  (fmt.Sprint(err) + ": " + stderr.String()),
			})
			return
		}
		c.JSON(200, gin.H{
			"status": "Delete QRCode success",
			"error":  (fmt.Sprint(err) + ": " + stderr.String()),
		})
	})

	router.GET("/cleardisk", func(c *gin.Context) {

		shPath := "/Users/kidswant/Bot/cleardisk.sh"
		openCmd := "bash"
		cmd := exec.Command(openCmd, shPath)
		var out bytes.Buffer
		var stderr bytes.Buffer
		cmd.Stdout = &out
		cmd.Stderr = &stderr
		err := cmd.Run()
		if err != nil {
			c.JSON(200, gin.H{
				"message": fmt.Sprint(err) + ": " + stderr.String(),
			})
			return
		}
		c.JSON(200, gin.H{
			"message": "clear disk success",
		})
	})

	router.GET("/checkQrcodeExist/:manager_user_id", func(c *gin.Context) {

		// 工号 require
		number := c.Param("manager_user_id")

		if len(number) <= 0 {
			c.JSON(200, gin.H{
				"code": "2001",
				"msg":  "工号不能为空",
			})
			return
		}

		imgPath := "/Users/kidswant/Desktop/wechat_write_path/" + number + ".jpeg"

		if _, err := os.Stat(imgPath); err == nil {
			// QRCode image exists
			c.Writer.Header().Set("Content-Type", "image/jpeg")
			QRCodeImgFile, _ := os.Open(imgPath)
			defer QRCodeImgFile.Close()
			io.Copy(c.Writer, QRCodeImgFile)
			return
		} else {
			c.JSON(200, gin.H{
				"code": "2001",
				"msg":  "二维码不存在",
			})
		}
	})

	router.GET("/status", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"code":    1001,
			"version": "1.1",
			"msg":     "server is ok",
		})
	})

	router.Run(":3003")
}
